package com.cskaoyan.util;

import net.sf.cglib.proxy.Enhancer;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author stone
 * @date 2022/03/17 11:55
 */
public class ProxyUtil {

    public static <T> T getServiceProxy(Class<T> target) {
        T proxy = null;
        if (target.isInterface()) {
            throw new RuntimeException("请传入实现类");
        } else {
            try {
                proxy = generateCglibProxy(target);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        }
        return proxy;
    }

    private static <T> T generateCglibProxy(Class<T> target) throws IllegalAccessException, InstantiationException {
        T instance = target.newInstance();
        T proxy = (T) Enhancer.create(target, new net.sf.cglib.proxy.InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                TransactionUtils.startTransaction();
                Object invoke = null;
                try {
                    invoke = method.invoke(instance, args);
                } catch (Exception e) {
                    TransactionUtils.rollBackTransaction();
                    e.printStackTrace();
                }
                TransactionUtils.commitTransaction();
                return invoke;
            }
        });
        return proxy;
    }


}
